#!/bin/bash
#set -x
Key=e8813f09-5262-4cca-9b76-b5cd1ba19379
api_sendfile="https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=${Key}&type=file"
api_post="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${Key}"

check-arguments (){
if  [[ -z "$1" ]] || [[ -z "$2" ]]
then
    sleep 0.3
    echo -e "\033[31mThis script requires exactly  arguments.\033[0m"
    cat <<EOF
    Usage:
    1)  $0 sendfile filename
    2)  $0 sendcontent [content] [mobilephone]
EOF
    exit 99
fi
}
send-content () {
curl ${api_post} -H 'Content-Type: application/json' -d '{"msgtype": "text", "text": {"content": "'${1}'","mentioned_mobile_list":["'${2}'"]}}'
# $1是内容，$2是需要@的人，填入电话号码
# 由于是位参传入，暂不支持空格
}
send-file () {
#media_id=$(curl -s -H 'Content-Type: multipart/form-data' ${api_sendfile} -F "media=@$1" | jq -r .media_id)
#media_id=$(curl -s -H 'Content-Type: multipart/form-data' ${api_sendfile} -F "media=@$1" |awk -F'"' '{print $14}')
media_id=$(curl -s -H 'Content-Type: multipart/form-data' ${api_sendfile} -F "media=@$1" |sed -n 's/.*"media_id":"\([^"]*\)".*/\1/p')
# 上传文件并获取media_id
curl ${api_post} -H 'Content-Type: application/json' -d '{"msgtype": "file", "file": {"media_id": "'$media_id'"}}'
# 通过media_id发送文件至企业微信
}


#check-arguments
case $1 in
        -h)
                check-arguments
                ;;
        sendfile)
                send-file $2 ;;
        sendcontent)
                send-content $2 $3 ;;
        *)
                echo -e "\033[33;5mrguments error.\033[0m\n"
                sleep 0.5
                check-arguments
                ;;
esac
